<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入搜索内容" v-model="userQueryInfo.query"  clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
           </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table stripe style="width: 100%" border :data="userList">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话" ></el-table-column>
        <el-table-column prop="role_name" label="角色" ></el-table-column>
        <el-table-column prop="mg_state" label="状态" >
          <template v-slot="slotScope">
            <el-switch
              v-model="slotScope.row.mg_state"
              @change="updataState(slotScope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template v-slot="slotScope">
            <div>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="userEdit(slotScope.row.id)"></el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="userDel(slotScope.row.id)"></el-button>
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="userSet(slotScope.row)"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userQueryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="userQueryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleClose">
      <el-form ref="addUserFormRef" :model="addUserForm" :rules="addUserFormRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" :disabled="title === '修改用户'"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!addUserForm.id">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setDialogVisible"
      width="50%"
      @close="sethandleClose">
      <span>当前的用户：{{ userInfo.username }}</span><br>
      <span>当前的角色：{{ userInfo.role_name}}</span><br>
      <span>分配新角色：</span>
      <el-select v-model="value" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义手机号校验规则
    const mobilValidator = (rule, value, callback) => {
      const parten = /^1[3|4|5|7|8][0-9]{9}$/
      if (parten.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入正确的手机号'))
      }
    }
    // 自定义邮箱验证规则
    const emailValidator = (rule, value, callback) => {
      const parten = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (parten.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入正确的邮箱地址'))
      }
    }
    return {
      // 用户列表
      userList: [],
      // 用户数据总数
      total: 0,
      userQueryInfo: {
        // 查询参数
        query: null,
        // 当前页码
        pagenum: 1,
        // 每页条数
        pagesize: 10
      },
      // 添加、编辑对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailValidator, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobilValidator, trigger: 'blur' }
        ]
      },
      // 分配角色对话框
      setDialogVisible: false,
      // 进行角色分配的用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      value: ''
    }
  },
  computed: {
    title () {
      return this.addUserForm.id ? '修改用户' : '新增用户'
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户数据列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.userQueryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户数据列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改分页数据
    // 修改每页条数
    handleSizeChange () {},
    // 修改页码
    handleCurrentChange () {},
    // 编辑用户
    async userEdit (id) {
      // 根据id获取用户详细信息
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.addUserForm = res.data
      this.addDialogVisible = true
    },
    // 删除用户
    async userDel (id) {
      const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm === 'confirm') {
        // 确认删除
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getUserList()
      }
    },
    // 分配权限
    async userSet (user) {
      // 获取所有角色数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      this.userInfo = user
      this.setDialogVisible = true
    },
    // 添加用户
    addUser () {
      this.addDialogVisible = true
    },
    // 修改用户状态
    async updataState (info) {
      const { data: res } = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state
        return this.$message.error('更新用户状态失败')
      }
      return this.$message.success('更新用户状态成功')
    },
    // 添加，编辑对话框的关闭事件
    handleClose () {
      console.log(2)
      this.$refs.addUserFormRef.resetFields()
      this.addUserForm = {}
      this.addDialogVisible = false
    },
    // 添加，编辑对话框的提交事件
    addBtn () {
      // 进行表单预校验
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入正确的用户信息')
        // 判断是新增还是编辑
        if (this.addUserForm.id) {
          // 存在ID说明是编辑
          const { data: res } = await this.$http.put(`users/${this.addUserForm.id}`, {
            email: this.addUserForm.email,
            mobile: this.addUserForm.mobile
          })
          if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
          this.addDialogVisible = false
          this.$message.success('修改用户信息成功')
          this.getUserList()
        } else {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          if (res.meta.status !== 201) return this.$message.error('添加用户失败')
          this.addDialogVisible = false
          this.$message.success('添加用户成功')
          this.getUserList()
        }
      })
    },
    // 分配角色对话框的关闭事件
    sethandleClose () {
      this.value = ''
      console.log(this.value)
      this.userInfo = {}
    },
    // 分配角色对话框的提交事件
    async setBtn () {
      if (!this.value) return this.$message.error('请选择角色')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.value
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setDialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">

</style>
